﻿using UnityEngine;
using System.Collections;

public class TargetSpawner : MonoBehaviour 
{
	public Background BGComp 		= null;
	public GameObject TargetPrefab 	= null;
	public int MaxLife 				= 4;

	public float SpawningTime		= 0.2f;

	private float m_StartX 			= 0.0f;

	private float m_CurrentTime 	= 0.0f;

	// Use this for initialization
	void Start ()
	{
		if ( TargetPrefab == null || BGComp == null )
		{
			Debug.LogError("No Target prefab or Background component set!!!");
			Destroy( this );
		}
		else
		{
			m_StartX 	= -Camera.main.orthographicSize * Camera.main.aspect;
			m_StartX 	-= TargetPrefab.transform.localScale.x;
		}
	}
	
	// Update is called once per frame
	void Update ()
	{
		m_CurrentTime -= Time.deltaTime;

		if ( m_CurrentTime < 0.0f )
		{
			// Spawn time!
			m_CurrentTime = SpawningTime;

			GameObject NewTargetGO = Instantiate(
				TargetPrefab, 
				new Vector3( m_StartX, Random.Range( -Camera.main.orthographicSize, Camera.main.orthographicSize ), 0.0f ),
				Quaternion.identity ) as GameObject;
			NewTargetGO.transform.parent = transform;

			Target NewTargetComp = NewTargetGO.GetComponent< Target >();
			NewTargetComp.Setup( 
				Random.Range( 0, BGComp.NumAlphaCuts + 1 ),
				Random.Range( 1, MaxLife ),
				BGComp );
		}
	}
}
